<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>两个球相撞</title>
</head>
<style>
    div {
        text-align: center;
        margin-top: 150px;
        border: 1px solid gray;
        background-color: #000000
    }
</style>

<body>
    <div>
        <canvas id="canvas" width="500px" height="500px"></canvas>
    </div>
    <script>
       window.requestAnimFrame = (function(){
    return window.requestAnimationFrame       || 
        window.webkitRequestAnimationFrame || 
        window.mozRequestAnimationFrame    || 
        window.oRequestAnimationFrame      || 
        window.msRequestAnimationFrame     ||
        function(callback){
            window.setTimeout(callback, 1000 / 60);
        };
})();
var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d'),
    w = canvas.width,
    h = canvas.height,
    posX = 20,
    posY = 20,
    speedX = 2,//小球X轴速度
    speedY = 2,//小球Y轴速度
    startSpeedX = 2,//小球X轴初始速度
    startSpeedY = 2,//小球Y轴初始速度
    radius = 20;//小球半径

    function ani(){       
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        posX += speedX;
        posY += speedY;
        
        //小球碰壁反弹
        if(posY > h - radius){ 
            speedY*=-1;
        }
        if(posX > w - radius){
            speedX*=-1;  
        }
        if(posY < radius){
            speedY = startSpeedY;
            posY = radius;
        }
        if(posX < radius){
            speedX = startSpeedX;
            posX = radius;
        }
        
        ctx.beginPath();
        ctx.arc(posX,posY,radius,0,2*Math.PI);
        ctx.fillStyle = '#fff';
        ctx.closePath();
        ctx.fill();
        requestAnimFrame(ani);
    }

    ani();
    </script>
</body>

</html>